package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.constant.insure.InsureConstant;
import com.itheima.sfbx.framework.commons.dto.basic.TreeItemVO;
import com.itheima.sfbx.framework.commons.dto.basic.TreeVO;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.NoProcessing;
import com.itheima.sfbx.insurance.dto.CategoryCoefficentVO;
import com.itheima.sfbx.insurance.dto.CategoryConditionVO;
import com.itheima.sfbx.insurance.dto.CategorySafeguardVO;
import com.itheima.sfbx.insurance.dto.CategoryVO;
import com.itheima.sfbx.insurance.enums.CategoryEnum;
import com.itheima.sfbx.insurance.mapper.CategoryMapper;
import com.itheima.sfbx.insurance.pojo.Category;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：保险分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryConditionService categoryConditionService;

    @Autowired
    ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    ICategorySafeguardService categorySafeguardService;


    private LambdaQueryWrapper<Category> queryWrapper(CategoryVO vo){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(vo.getParentCategoryNo()),Category::getParentCategoryNo,vo.getCategoryNo());
        wrapper.eq(StrUtil.isNotBlank(vo.getCategoryNo()),Category::getCategoryNo,vo.getCategoryNo());
        wrapper.like(StrUtil.isNotBlank(vo.getCategoryName()),Category::getCategoryName,vo.getCategoryName());
        wrapper.eq(StrUtil.isNotBlank(vo.getDataState()),Category::getDataState,vo.getDataState());
        wrapper.eq(StrUtil.isNotBlank(vo.getCategoryType()),Category::getCategoryType,vo.getCategoryType());
        wrapper.eq(StrUtil.isNotBlank(vo.getLeafNode()),Category::getLeafNode,vo.getLeafNode());
        wrapper.eq(StrUtil.isNotBlank(vo.getShowIndex()),Category::getShowIndex,vo.getShowIndex());
        return wrapper;
    }
    private void setCategoryVoList(List<CategoryVO> records){
        Set<String> set = records.stream().map(CategoryVO::getCategoryNo).collect(Collectors.toSet());
        List<CategoryCondition> list = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getCategoryNo, set)
                .list();
        Map<String, List<CategoryCondition>> conditionMap = list.stream().collect(Collectors.groupingBy(CategoryCondition::getCategoryNo));
        List<CategoryCoefficent> list1 = categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCategoryNo, set)
                .list();
        Map<String, List<CategoryCoefficent>> coefficentMap = list1.stream().collect(Collectors.groupingBy(CategoryCoefficent::getCategoryNo));
        List<CategorySafeguard> list2 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getCategoryNo, set)
                .list();
        Map<String, List<CategorySafeguard>> safeMap = list2.stream().collect(Collectors.groupingBy(CategorySafeguard::getCategoryNo));
        for (CategoryVO vo : records) {
            List<CategorySafeguard> safeguards = safeMap.get(vo.getCategoryNo());
            vo.setCategorySafeguardVOs(BeanConv.toBeanList(safeguards, CategorySafeguardVO.class));
            List<CategoryCoefficent> categoryCoefficents = coefficentMap.get(vo.getCategoryNo());
            vo.setCategoryCoefficentVOs(BeanConv.toBeanList(categoryCoefficents, CategoryCoefficentVO.class));
            List<CategoryCondition> conditions = conditionMap.get(vo.getCategoryNo());
            vo.setCategoryConditionVOs(BeanConv.toBeanList(conditions, CategoryConditionVO.class));
        }
    }
    @Override
    public Page<CategoryVO> findPage(CategoryVO categoryVO, int pageNum, int pageSize) {
        //构造查询条件
        LambdaQueryWrapper<Category> wrapper = queryWrapper(categoryVO);
        Page<Category> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        Page<CategoryVO> voPage = BeanConv.toPage(page, CategoryVO.class);
        List<CategoryVO> records = voPage.getRecords();
        if(CollUtil.isEmpty(records)){
            //没有查询到结果
            return voPage;
        }
        setCategoryVoList(records);
        return voPage;
    }

    @Override
    @Transactional
    public CategoryVO save(CategoryVO categoryVO) {
        String categoryNo = createCategoryNo(categoryVO.getParentCategoryNo());
        categoryVO.setCategoryNo(categoryNo);
        Category bean = BeanConv.toBean(categoryVO, Category.class);
        this.save(bean);
        saveCollection(categoryVO);
        return BeanConv.toBean(bean, CategoryVO.class);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveCollection(CategoryVO categoryVO){
        List<CategoryCoefficentVO> coefficentVOs = categoryVO.getCategoryCoefficentVOs();
        if(CollUtil.isNotEmpty(coefficentVOs)){
            for (CategoryCoefficentVO vo : coefficentVOs) {
                vo.setCategoryNo(categoryVO.getCategoryNo());
            }
            categoryCoefficentService.saveBatch(BeanConv.toBeanList(coefficentVOs,CategoryCoefficent.class));
        }
        List<CategoryConditionVO> conditionVOs = categoryVO.getCategoryConditionVOs();
        if(CollUtil.isNotEmpty(conditionVOs)){
            for (CategoryConditionVO vo : conditionVOs) {
                vo.setCategoryNo(categoryVO.getCategoryNo());
            }
            categoryConditionService.saveBatch(BeanConv.toBeanList(conditionVOs,CategoryCondition.class));
        }
        List<CategorySafeguardVO> safeguardVOs = categoryVO.getCategorySafeguardVOs();
        if(CollUtil.isNotEmpty(safeguardVOs)){
            for (CategorySafeguardVO vo : safeguardVOs) {
                vo.setCategoryNo(categoryVO.getCategoryNo());
            }
            categorySafeguardService.saveBatch(BeanConv.toBeanList(safeguardVOs,CategorySafeguard.class));
        }
    }
    @Override
    @Transactional
    public Boolean update(CategoryVO categoryVO) {
        Category category = this.getById(categoryVO.getId());
        if(category==null){
            throw new ProjectException(CategoryEnum.UPDATE_FAIL);
        }
        //更新
        this.updateById(BeanConv.toBean(categoryVO, Category.class));
        //删除数据库中的关联关系
        categoryCoefficentService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categorySafeguardService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categoryConditionService.deleteByCategoryNo(categoryVO.getCategoryNo());

        //新增
        saveCollection(categoryVO);
        return true;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        List<Long> ids=new ArrayList<>();
        if(checkedIds.length>0) {
            for (int i = 0; i < checkedIds.length; i++) {
                ids.add(Long.valueOf(checkedIds[i]));
            }
        }
        List<Category> list = this.listByIds(ids);
        List<Category> list1=new ArrayList<>();
        for (Category category : list) {
            String s = NoProcessing.processString(category.getCategoryNo());
            List<Category> list2 = this.lambdaQuery()
                    .likeRight(Category::getParentCategoryNo, Long.valueOf(s))
                    .list();
            if(CollUtil.isNotEmpty(list2)) {
                list1.addAll(list2);
            }
        }

        if(CollUtil.isNotEmpty(list1)){
            throw new ProjectException(CategoryEnum.DEL_FAIL);
        }
        if(CollUtil.isEmpty(list)){
            return true;
        }
        List<String> collect = list.stream().map(Category::getCategoryNo).collect(Collectors.toList());
        //删除
        this.removeByIds(ids);
        //删除数据库中的关联关系
        categoryCoefficentService.deleteByCategoryNos(collect);
        categorySafeguardService.deleteByCategoryNos(collect);
        categoryConditionService.deleteByCategoryNos(collect);
        return true;
    }

    @Override
    public List<CategoryVO> findList(CategoryVO categoryVO) {
        LambdaQueryWrapper<Category> wrapper = queryWrapper(categoryVO);
        List<Category> list = this.list(wrapper);
        List<CategoryVO> voList = BeanConv.toBeanList(list, CategoryVO.class);
        //筛除层级不对的vo
        if(CollUtil.isNotEmpty(voList)&&CollUtil.isNotEmpty(categoryVO.getNodeFloors())) {
            voList=voList.stream().filter(vo->{
                long leavel=NoProcessing.processString(vo.getCategoryNo()).length()/3-1;
                return categoryVO.getNodeFloors().contains(leavel);
            }).collect(Collectors.toList());
        }
        //设置缺少的属性
        setCategoryVoList(voList);
        return voList;
    }



    @Override
    public TreeVO categoryTreeVO(String parentCategoryNo, String categoryType,String[] checkedCategoryNos) {
        //确定根节点
        String rootNo = parentCategoryNo == null ? SuperConstant.ROOT_PARENT_ID : parentCategoryNo;
        //查询根节点下的所有子节点
        String s = NoProcessing.processString(rootNo);
        List<Category> list = this.lambdaQuery()
                .likeRight(Category::getCategoryNo, s)
                .eq(StrUtil.isNotBlank(categoryType), Category::getCategoryType, categoryType)
                .list();
        //转为TreeItemVO类型
        List<TreeItemVO> collect = list.stream().map(ca -> TreeItemVO.builder()
                .id(ca.getCategoryNo())
                .parentId(ca.getParentCategoryNo())
                .label(ca.getCategoryName())
                .build()).collect(Collectors.toList());
        //转为map
        Map<String, List<TreeItemVO>> treeMap = collect.stream().collect(Collectors.groupingBy(TreeItemVO::getParentId));
        //将节点的关系挂到对应的位置
        for (TreeItemVO itemVO : collect) {
            //找到他的所有子节点
            List<TreeItemVO> treeItemVOS = treeMap.get(itemVO.getId());
            //设置他的子节点
            itemVO.setChildren(treeItemVOS);
        }
        //封装treevo，顶级节点
        return TreeVO.builder()
                .items(treeMap.get(rootNo))
                .build();
    }

    @Override
    public String createCategoryNo(String parentCategoryNo) {
        CategoryVO categoryVO = CategoryVO.builder()
            .parentCategoryNo(parentCategoryNo)
            .build();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentCategoryNo,parentCategoryNo);
        List<Category> categoryList = list(queryWrapper);
        //无下属节点则创建下属节点
        if (EmptyUtil.isNullOrEmpty(categoryList)){
            return NoProcessing.createNo(parentCategoryNo,false);
        //有下属节点则累加下属节点
        }else {
            Long categoryNo = categoryList.stream()
                .map(category -> { return Long.valueOf(category.getCategoryNo());})
                .max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(categoryNo),true);
        }
    }

    /**
     * 人种榜险种榜分类
      * @param type
     */
    @Override
    public List<CategoryVO> categoryCheckRule(String type) {
        //判断是否是险种榜
        if(InsureConstant.checkIsInsureType(type)){
            List<CategoryVO> res = new ArrayList<>();
            //获取所有的险种榜
            List<String> allCheckRule = InsureConstant.getAllCheckRule();
            allCheckRule.forEach(e->{
                CategoryVO categoryVO = CategoryVO.builder().categoryNo(e).categoryName(InsureConstant.getRuleNameById(e)).build();
                res.add(categoryVO);
            });
            return res;
        }else{
            //说明是人种榜
            List<String> categoryNames = Arrays.asList("成年人", "少儿", "老人");
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Category::getCategoryName,categoryNames);
            queryWrapper.eq(Category::getDataState,SuperConstant.DATA_STATE_0);
            List<CategoryVO> res = BeanConv.toBeanList(list(queryWrapper), CategoryVO.class);
            return res;
        }
    }
}
